﻿/**
 * Copyright (c) 2013 Jeremy Wyman
 * Microsoft Public License (Ms-PL)
 * This license governs use of the accompanying software. If you use the software, you accept this license. If you do not accept the license, do not use the software.
 * 1. Definitions
 *    The terms "reproduce", "reproduction", "derivative works", and "distribution" have the same meaning here as under U.S. copyright law.
 *    A "contribution" is the original software, or any additions or changes to the software.
 *    A "contributor" is any person that distributes its contribution under this license.
 *    "Licensed patents" are a contributor's patent claims that read directly on its contribution.
 * 2. Grant of Rights
 *    (A) Copyright Grant - Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free copyright license to reproduce its contribution, prepare derivative works of its contribution, and distribute its contribution or any derivative works that you create.
 *    (B) Patent Grant - Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free license under its licensed patents to make, have made, use, sell, offer for sale, import, and/or otherwise dispose of its contribution in the software or derivative works of the contribution in the software.
 * 3. Conditions and Limitations
 *    (A) No Trademark License - This license does not grant you rights to use any contributors' name, logo, or trademarks.
 *    (B) If you bring a patent claim against any contributor over patents that you claim are infringed by the software, your patent license from such contributor to the software ends automatically.
 *    (C) If you distribute any portion of the software, you must retain all copyright, patent, trademark, and attribution notices that are present in the software.
 *    (D) If you distribute any portion of the software in source code form, you may do so only under this license by including a complete copy of this license with your distribution. If you distribute any portion of the software in compiled or object code form, you may only do so under a license that complies with this license.
 *    (E) The software is licensed "as-is." You bear the risk of using it. The contributors give no express warranties, guarantees or conditions. You may have additional consumer rights under your local laws which this license cannot change. To the extent permitted under your local laws, the contributors exclude the implied warranties of merchantability, fitness for a particular purpose and non-infringement.
 *    
 * More info on: http://tempest.codeplex.com
**/

using System;
using System.Collections.Generic;
using System.Text;

namespace Tempest
{
    internal static partial class CommandLine
    {
        #region Constants
        private static char TOKEN_NULL = '\0';
        public static char[] TOKEN_ASSIGNMENT = { '=', ':' };
        public static char[] TOKEN_PARAMETER = { '-', '/' };
        #endregion
        #region Constructors
        static CommandLine() { }
        #endregion
        #region Members
        /// <summary>
        /// 
        /// </summary>
        public static bool IsEmpty { get { return GetOptions().Count == 0; } }
        /// <summary>
        /// 
        /// </summary>
        public static int Length { get { return GetOptions().Count; } }
        /* private members */
        private static List<Option> _options;
        #endregion
        #region Methods
        /// <summary>
        /// Returns a list of options from the command line. Designed to mimick PERL's GetOpts function.
        /// </summary>
        /// <returns>List of the command line options sent to the program by the OS</returns>
        public static List<Option> GetOptions()
        {
            if (_options == null)
            {
                string[] commandLineArguments = Environment.GetCommandLineArgs();
                Dictionary<string, Option> optionList = new Dictionary<string, Option>();
                string parameter = null,
                       value = null;
                int index = 0;
                char parameterToken = TOKEN_NULL;
                OptionType type = OptionType.Unknown;
                // loop through all the arguments (skipping the first), processing them
                for (int i = 1; i < commandLineArguments.Length; i++)
                {
                    parameter = commandLineArguments[i];

                    if (parameterToken == TOKEN_NULL)
                    {
                        foreach (char controlToken in TOKEN_PARAMETER)
                        {
                            if (parameter[0] == controlToken)
                            {
                                parameterToken = controlToken;
                                break;
                            }
                        }
                    }
                    // clean up the parameter
                    parameter = parameter.Trim(TOKEN_ASSIGNMENT);
                    // break it into its parts
                    int idx = parameter.IndexOfAny(TOKEN_ASSIGNMENT);
                    // if there are more than a single part, assume the second part is the value
                    if (parameter[0] == parameterToken && idx > -1)
                    {
                        value = parameter.Substring(idx).Trim(TOKEN_ASSIGNMENT);
                        parameter = parameter.Substring(0, idx).Trim(TOKEN_ASSIGNMENT);
                        type |= OptionType.Assignment;
                    }
                    //
                    if (parameter.Length > 1 && parameter[0] == parameterToken)
                    {
                        if (parameter.Length > 2 && parameter[1] == parameterToken)
                        {
                            type |= OptionType.LongForm;
                            parameter = parameter.Substring(2);
                        }
                        else
                        {
                            type |= OptionType.ShortForm;
                            parameter = parameter.Substring(1);
                        }
                        // skip null values
                        if (value == null)
                        {
                            // look ahead and see if the next value is something that can be take as a value
                            if (i + 1 < commandLineArguments.Length && commandLineArguments[i + 1][0] != parameterToken)
                            {
                                type |= OptionType.Assignment;
                                value = commandLineArguments[++i];
                            }
                            else
                            {
                                type |= OptionType.Command;
                                value = String.Empty;
                            }
                        }
                    }
                    else
                    {
                        type = OptionType.Text;
                        // text values are the parameter
                        value = parameter;
                        parameter = "TEXT" + (index + 1);
                    }
                    //
                    if (optionList.ContainsKey(parameter))
                    {
                        optionList.Remove(parameter);
                    }
                    //
                    optionList.Add(parameter, new Option(parameter, value, index++, type));
                    // clear the parameter and value variables
                    parameter = null;
                    value = null;
                    type = OptionType.Unknown;
                }
                // add each option to the result list
                _options = new List<Option>();
                foreach (Option option in optionList.Values)
                {
                    _options.Add(option);
                }
            }
            return _options;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="index"></param>
        /// <returns></returns>
        public static string GetParameter(int index)
        {
            string parameter = null;
            if (index < Length)
            {
                parameter = GetOptions()[index].Parameter;
            }
            return parameter;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="index"></param>
        /// <returns></returns>
        public static string GetValue(int index)
        {
            string value = null;
            if (index < Length)
            {
                value = GetOptions()[index].Value;
            }
            return value;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="match"></param>
        /// <returns></returns>
        public static string GetValue(string parameter)
        {
            string value = null;
            string[] parameters = parameter.Split('|');
            //
            for (int i = 0; value == null && i < parameters.Length; i++)
            {
                foreach (Option option in GetOptions())
                {
                    if (parameters[i].Equals(option.Parameter, StringComparison.OrdinalIgnoreCase))
                    {
                        if ((option.Type & OptionType.Assignment) != OptionType.Unknown)
                        {
                            value = option.Value;
                        }
                        else
                        {
                            value = option.Parameter;
                        }
                        break;
                    }
                }
            }
            //
            return value;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="parameter"></param>
        /// <returns></returns>
        public static bool ParameterExists(string parameter)
        {
            string[] parameters = parameter.Split('|');
            bool exists = false;
            for (int i = 0; !exists && i < parameters.Length; i++)
            {
                foreach (Option option in GetOptions())
                {
                    if (option.Parameter.Equals(parameters[i], StringComparison.OrdinalIgnoreCase))
                    {
                        exists = true;
                        break;
                    }
                }
            }
            return exists;
        }
        #endregion
    }
}